#include "test_common.hpp"
#include "tools/api.hpp"
#include <filesystem>
#include <fstream>

namespace fs = std::filesystem;

void test_extractSameNameFile()
{
    std::string testDir = test_common::getTestTempDir();
    std::string dir1 = testDir + "/dir1";
    std::string dir2 = testDir + "/dir2";
    test_common::cleanupTestDir(testDir);
    
    MKDIR(dir1);
    MKDIR(dir2);
    
    // 创建同名文件
    TOUCH(dir1 + "/file1.txt");
    TOUCH(dir1 + "/file2.txt");
    TOUCH(dir2 + "/file1.txt");
    TOUCH(dir2 + "/file3.txt");
    
    std::vector<std::string> result;
    bool ret = COMPARE_DIR(dir1, dir2, result);
    
    ASSERT_TRUE(ret);
    ASSERT_TRUE(result.size() >= 1);
    // file1 应该在结果中
    bool found = false;
    for (const auto& name : result) {
        if (name == "file1") {
            found = true;
            break;
        }
    }
    ASSERT_TRUE(found);
    
    test_common::cleanupTestDir(testDir);
}

void test_filtrateFileFromCSV()
{
    std::string testDir = test_common::getTestTempDir();
    std::string csvFile = testDir + "/test.csv";
    std::string sourceDir = testDir + "/source";
    std::string targetDir = testDir + "/target";
    test_common::cleanupTestDir(testDir);
    
    MKDIR(sourceDir);
    MKDIR(targetDir);
    
    // 创建源文件
    TOUCH(sourceDir + "/file1.txt");
    TOUCH(sourceDir + "/file2.txt");
    TOUCH(sourceDir + "/file3.txt");
    
    // 创建CSV文件
    {
        std::ofstream csv(csvFile);
        csv << "file1\n";
        csv << "file2\n";
        csv.close();
    }
    
    bool ret = GET_FILE(csvFile, sourceDir, targetDir);
    ASSERT_TRUE(ret);
    
    // 检查目标目录中是否有文件
    std::vector<std::string> targetFiles;
    LS(targetDir, targetFiles);
    ASSERT_TRUE(targetFiles.size() >= 2);
    
    test_common::cleanupTestDir(testDir);
}

int main()
{
    auto& runner = test_common::TestRunner::getInstance();
    runner.reset();
    
    std::cout << "=== Running File Module Tests ===" << std::endl;
    
    runner.runTest("test_extractSameNameFile", test_extractSameNameFile);
    runner.runTest("test_filtrateFileFromCSV", test_filtrateFileFromCSV);
    
    std::cout << "\n=== Test Results ===" << std::endl;
    std::cout << "Total: " << runner.getTotal() << std::endl;
    std::cout << "Passed: " << runner.getPassed() << std::endl;
    std::cout << "Failed: " << runner.getFailed() << std::endl;
    
    return runner.getFailed() == 0 ? 0 : 1;
}

